//
//  PGProductManager.m
//  PhotographicGuide
//
//  Created by indream on 13-6-22.
//  Copyright (c) 2013年 indream. All rights reserved.
//

#import "PGProductManager.h"
#import "PGHttpOperator.h"
#import "SBJson/SBJson.h"
static PGProductManager*_instance = nil;
static NSString* NOTIFICATION_PRODUCT_TABLE_REFRESH = @"__NOTIFICATION_PRODUCT_TABLE_REFRESH__";
static NSString* NOTIFICATION_PRODUCT_DATA_LOADED = @"__NOTIFICATION_PRODUCT_DATA_LOADED__";

static NSString*productURL = @"http://1.starrynightwalk.sinaapp.com/mobile/ios/app_product.php";

@implementation PGProductManager

-(id)init{
    self = [super init];
    if (self) {
        self.queue = [[NSOperationQueue alloc]init];
        ;
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(dataLoaded:) name:NOTIFICATION_PRODUCT_DATA_LOADED object:nil];

    }
    return self;
}
-(void)requestWithTag:(NSString*)tag{
    NSTimeInterval timeInterval = floor([[NSDate date]timeIntervalSince1970]/86400)*86400;
    [self addQperator:[[PGHttpOperator alloc]initWithURLString:[productURL stringByAppendingString:
                                                                [NSString stringWithFormat:@"?isdebug=0&count=%d&time=%d&tag=%@",10,(int)timeInterval,[tag stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]] cache:YES notification:NOTIFICATION_PRODUCT_DATA_LOADED]];
}

-(void)addQperator:(PGHttpOperator*)operator{
    [_queue addOperation:operator];
}
-(void)dataLoaded:(NSNotification*)notification{
    NSString*jsonData = [[NSString alloc]initWithData:[notification.userInfo objectForKey:@"data"] encoding:NSUTF8StringEncoding];
    SBJsonParser *parser = [[SBJsonParser alloc]init];
    NSDictionary*json = [parser objectWithString:jsonData];
    self.jsonData = json;
    if([[json objectForKey:@"code"]intValue]==0){

    }
    NSLog(@"product data loaded!!");
    [self performSelectorOnMainThread:@selector(postFinishLoad) withObject:nil waitUntilDone:YES];
}
-(void)postFinishLoad{
    [[NSNotificationCenter defaultCenter]postNotificationName:NOTIFICATION_PRODUCT_TABLE_REFRESH object:nil userInfo:self.jsonData];
}
+(PGProductManager*)sharedManager{
    if(_instance==nil){
        _instance = [[PGProductManager alloc]init];
    }
    return _instance;
}
@end
